import { createMemoryHistory, createRouter, createWebHistory } from 'vue-router'
/**
 * createMemoryHistory 浏览器不会显示路由地址, 无法通过修改路由地址访问页面
 * createWebHistory 浏览器会显示路由地址, 可以通过修改路由地址访问页面
 */

import { useLoginStore } from '@/stores/login.js'

import { contractRouter } from '@/views/contract/router.js'
import { clueRouter } from '@/views/clue/router.js'
import { homeRouter } from '@/views/home/router.js'
// import { indexRouter } from '@/views/index/router.js'
import { chargeRouter } from '@/views/charge/router.js'
import { errorRouter } from '@/views/error/router.js'

import { orderRouter } from '@/views/order/router.js'
import { commissionRouter } from '@/views/commission/router.js'

import {statRouter } from '@/views/stat/router.js' 
import { customerRouter } from '@/views/customer/router.js'
import {productRouter} from '@/views/product/router.js'
const routerList = [
  contractRouter,
  clueRouter,
  homeRouter,
  // indexRouter,
  chargeRouter,
  errorRouter,
  
  orderRouter,
  customerRouter,
  
  statRouter,
  commissionRouter,
  productRouter
] // 注册的路由列表


const redirect = [{ 
    path: '/index', 
    redirect: '/index/home'
}]
const pagePath = [{ 
    path: '/index', 
    component: import('@/views/index/Index.vue'), 
    name: 'Index',
    children: [{
      path: '/index/home',
      component: import('@/views/home/Home.vue'),
      name: 'Home'
  }]
}]

for (const item of routerList) {
  redirect.push(item.redirect)
  if (item.levelOne) {
    pagePath.push(item.pagePath)
  }
}
for (const item of routerList) {
  if (!item.levelOne) {
    if (item.parent) {
      const parent = pagePath.find(i => i.path == item.parent)
      if (parent) {
        if (!parent.children) {
          parent.children = []
        }
        parent.children.push(item.pagePath)
      }
    }
  }
}
const routes = [
  ...redirect,
  ...pagePath
]
console.log('routes', routes)
const router = createRouter({
  history: createWebHistory(),
  routes,
})

// router.beforeEach(async (to, from) => {
//   const loginStore = useLoginStore()
//   if(to.name != 'Login') {
//     if(!loginStore.token) {
//       return { name: 'Login' }
//     }
//   } else {
//     if(loginStore.token) {
//       return { name: from.name }
//     }
//   }
// })

export default router